package Tree;

import java.util.LinkedList;
import java.util.List;

public class p429N叉树的层序遍历 {
    class Solution {
        public List<List<Integer>> levelOrder(Node root) {
            List<List<Integer>> list = new LinkedList<>();
            if(root == null) return list;
            LinkedList<Node> queue = new LinkedList<>();

            queue.add(root);
            while(!queue.isEmpty()){
                int len = queue.size();
                List<Integer> itemList = new LinkedList<>();
                while(len > 0){
                    len--;
                    Node node = queue.poll();
                    itemList.add(node.val);
                    List<Node> children = node.children;
                    // 如果子节点为空，就看下一个结点
                    if(children == null || children.size() == 0) continue;
                    // 如果子节点不为空，遍历子节点，将其加入队列中
                    for(Node child : children){
                        if(child != null){
                            queue.add(child);
                        }
                    }
                }
                list.add(itemList);
            }
            return list;
        }
    }

    static class Node {
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }
}
}
